/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.pre.parser.get;

import cn.ac.iie.pre.parser.global.GlobalParas;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import org.apache.log4j.Logger;

/**
 *
 * @author moli
 */
public class ReadFile {

    public static Logger LOG = Logger.getLogger(ReadFile.class);

    public void getFile() throws InterruptedException, IOException {
        File dir = new File(GlobalParas.SOURCE_DIR);
        if (!dir.exists()) {
            LOG.error(dir.getAbsolutePath() + " dir does not exist.");
        }
        while (true) {
            String[] fileNameList = dir.list();
            LOG.debug("===========get file lists, the size is " + fileNameList.length + " files are " + Arrays.toString(fileNameList));
            for (String fileName : fileNameList) {
                if (fileName.endsWith(GlobalParas.UNTAR_SUS_SUFFIX) || fileName.endsWith(GlobalParas.READ_SUS_SUFFIX)) {
                    continue;
                }
                File file = new File(GlobalParas.SOURCE_DIR + "/" + fileName);
                File untarSusFile = new File(GlobalParas.SOURCE_DIR + "/" + fileName + GlobalParas.UNTAR_SUS_SUFFIX);
                File readSusFile = new File(GlobalParas.SOURCE_DIR + "/" + fileName + GlobalParas.READ_SUS_SUFFIX);

                if (file.exists() && untarSusFile.exists() && !readSusFile.exists()) {
                    GlobalParas.FILES_NAME_QUEUE.put(fileName);

                    LOG.info(String.format("put %s file to queue successfully.", fileName));
                    ReadFile.createReadSusFile(fileName);
                } 
            }

            Thread.sleep(1000);
        }
    }

    public static void createReadSusFile(String fileName) throws IOException {
        File file = new File(GlobalParas.SOURCE_DIR + "/" + fileName);
        if (!file.exists()) {
            LOG.error(String.format("%s file does not exist, can not create %s file", fileName, GlobalParas.READ_SUS_SUFFIX));
            return;
        }
        File readSusFile = new File(GlobalParas.SOURCE_DIR + "/" + fileName + GlobalParas.READ_SUS_SUFFIX);
        readSusFile.createNewFile();

        LOG.info(String.format("create %s file susccessfully for file %s", GlobalParas.READ_SUS_SUFFIX, fileName));
    }

}
